package com.mp.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mp.core.utils.*;
import com.mp.core.utils.common.RedisCommon;
import com.mp.enums.ActionEnum;
import com.mp.pojo.Admin;
import com.mp.pojo.NO.WebsiteFlyRecordNO;
import com.mp.pojo.Query.*;
import com.mp.pojo.VO.WebsiteFlyRecordVO;
import com.mp.pojo.VO.WebsiteGameVO;
import com.mp.pojo.WebsiteFlyRecord;
import com.mp.pojo.WebsiteGameSetting;
import com.mp.pojo.WebsiteSetUp;
import com.mp.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.ls.LSException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

/**
 *@description:
 *@author: Ace
 *@create: 2019-08-22 09:09
 */
@Api(value = "flyApi")
@RestController
@RequestMapping("/api/fly")
public class FlyApi {

    @Autowired
    private WebsiteGameService websiteGameService;

    @Autowired
    private WebsiteGameSettingService websiteGameSettingService;

    @Autowired
    private WebsiteFlyRecordService websiteFlyRecordService;

    @Autowired
    private WebsiteSetUpService websiteSetUpService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisCommon redisCommon;

    @Value("${php.checkFlyAdmin}")
    private String checkFlyAdmin;

    @Value("${php.sendGameSeal}")
    private String sendGameSeal;


    @ApiOperation(value = "查询站点游戏",response = WebsiteGameQuery.class)
    @PostMapping("/getWebsiteGameList")
    public JSONObject getWebsiteGameList(@Valid WebsiteGameQuery websiteGame){
        List<WebsiteGameVO> list = websiteGameService.getWebsiteGameList(websiteGame.getWebsiteId(),websiteGame.getAdminId());
        JSONObject result = new JSONObject();
        result.put("websiteGameList",list);
        return MrdJsonResult.ok(result);
    }

    @ApiOperation(value = "编辑站点游戏设置",response = WebsiteGameSettingEditQuery.class)
    @PostMapping("/editWebsiteGameSetting")
    public JSONObject editWebsiteGameSetting(@Valid WebsiteGameSettingEditQuery websiteGameSettingEdit, HttpServletResponse response){

        QueryWrapper<WebsiteGameSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_id",websiteGameSettingEdit.getAdminId());
        queryWrapper.eq("website_game_id",websiteGameSettingEdit.getWebsiteGameId());
        //查询是否存在
        WebsiteGameSetting getWebsiteGameSetting = websiteGameSettingService.getOne(queryWrapper);

        WebsiteGameSetting websiteGameSetting = new WebsiteGameSetting();
        BeanUtils.copyProperties(websiteGameSettingEdit,websiteGameSetting);
        JSONObject result = new JSONObject();
        if (getWebsiteGameSetting == null){
            //若不存在就添加
            boolean flag = websiteGameSettingService.save(websiteGameSetting);
            result.put("flag",flag);
        }else {
            //若存在就修改
            getWebsiteGameSetting.setStatus(websiteGameSetting.getStatus());
            boolean flag = websiteGameSettingService.updateById(getWebsiteGameSetting);
            result.put("flag",flag);
        }
        WebsiteGameVO websiteGameVO = websiteGameService.getGameInfo(websiteGameSettingEdit.getWebsiteGameId(),websiteGameSettingEdit.getAdminId());
        redisCommon.setGameStatus(websiteGameVO.getAccount(),websiteGameVO.getCode(),websiteGameVO.getStatus());
        return MrdJsonResult.ok(result);
    }

    @ApiOperation(value = "站点设置",response = WebsiteSetUpQuery.class)
    @PostMapping("/editWebsiteSetUp")
    public JSONObject editWebsiteSetUp(@Valid WebsiteSetUpQuery websiteSetUpQuery){
        QueryWrapper<WebsiteSetUp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("website_id",websiteSetUpQuery.getWebsiteId());
        //查询是否存在
        WebsiteSetUp getWgetWebsiteSetUp = websiteSetUpService.getOne(queryWrapper);
        WebsiteSetUp edit = new WebsiteSetUp();
        BeanUtils.copyProperties(websiteSetUpQuery,edit);
        JSONObject result = new JSONObject();
        if (getWgetWebsiteSetUp == null){
            boolean  flag = websiteSetUpService.save(edit);
            result.put("flag",flag);
        }else {
            getWgetWebsiteSetUp.setState(edit.getState());
            getWgetWebsiteSetUp.setLoginFailNumber(edit.getLoginFailNumber());
            getWgetWebsiteSetUp.setDeleteDataNumber(edit.getDeleteDataNumber());
            boolean flag = websiteSetUpService.updateById(getWgetWebsiteSetUp);
            result.put("flag",flag);
        }
        return MrdJsonResult.ok(result);
    }

    @ApiOperation(value = "查询站点设置",response = selectWebsiteSetUpQuery.class)
    @PostMapping("/getWebsiteSetUp")
    public JSONObject getWebsiteSetUp(@Valid selectWebsiteSetUpQuery websiteSetUpQuery){
        QueryWrapper<WebsiteSetUp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("website_id",websiteSetUpQuery.getWebsiteId());
        JSONObject result = new JSONObject();
        WebsiteSetUp websiteSetUp = websiteSetUpService.getOne(queryWrapper);
        result.put("websiteSetUp",websiteSetUp);
        return MrdJsonResult.ok(result);
    }

    @ApiOperation(value = "登录",response = LoginQuery.class)
    @PostMapping("/login")
    public JSONObject login(@Valid LoginQuery login){
        try {
            //获取PHP管理员是否存在
            String flyLogin = sendFlyAdmin(login.getAccount(), login.getPassword());
            JSONObject json = JSONObject.parseObject(flyLogin);
            String request = (String) json.get("data");
            System.out.println("------------"+json.get("code"));
            if (StringUtils.isEmpty(request)){
                return MrdJsonResult.build1000("账号或密码错误！");
            }else{
                QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("account",login.getAccount());
                //查询是否存在改管理员账号
                Admin  isAdmin = adminService.getOne(queryWrapper);
                if (isAdmin !=null){
                    String token = UUID.randomUUID().toString().replace("-", "");
                    isAdmin.setToken(token);
                    adminService.updateById(isAdmin);
                    JSONObject result = new JSONObject();
                    result.put("adminInfo",isAdmin);
                    return MrdJsonResult.ok(result);
                }else {
                    Admin admin = new Admin();
                    admin.setAccount(login.getAccount());
                    admin.setToken((UUID.randomUUID().toString().replace("-","")));
                    BeanUtils.copyProperties(login,admin);
                    adminService.save(admin);
                    JSONObject result = new JSONObject();
                    result.put("adminInfo",admin);
                    return MrdJsonResult.ok(result);
                }
            }
        }catch (Exception e){
            return MrdJsonResult.build1000("链接超时,尝试重新登录！");
        }
    }

    @ApiOperation(value = "站点飞单记录",response = WebsiteFlyRecordQuery.class)
    @PostMapping("/pageWebsiteFlyRecord")
    public JSONObject pageWebsiteFlyRecord(WebsiteFlyRecordNO flyRecord){
        if (Utils.isNull(new Object[]{flyRecord.getWebsiteUserId(),flyRecord.getCode(),flyRecord.getSize(),flyRecord.getCurrent()})){
            return MrdJsonResult.build503();
        }
        IPage<WebsiteFlyRecordVO> page = websiteFlyRecordService.pageWebsiteFlyRecord(flyRecord);
        return MrdJsonResult.ok(page);
    }

    @ApiOperation(value = "删除站点飞单记录",response = DelWebsiteFlyRecordQuery.class)
    @PostMapping("/delWebsiteFlyRecord")
    public JSONObject delWebsiteFlyRecord(@Valid DelWebsiteFlyRecordQuery delWebsiteFlyRecordQuery){
        try {
            QueryWrapper<WebsiteSetUp> websiteSetUpQueryWrapper = new QueryWrapper<>();
            websiteSetUpQueryWrapper.eq("website_id",delWebsiteFlyRecordQuery.getWebsiteId());
            WebsiteSetUp websiteSetUp = websiteSetUpService.getOne(websiteSetUpQueryWrapper);
            if (websiteSetUp.getState().equals(1)){
                QueryWrapper<WebsiteFlyRecord> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("website_user_id",delWebsiteFlyRecordQuery.getWebsiteUserId());
                queryWrapper.eq("website_game_id",delWebsiteFlyRecordQuery.getWebsiteGameId());
                List<WebsiteFlyRecord> list = websiteFlyRecordService.list(queryWrapper);
                if (delWebsiteFlyRecordQuery.getDelAmount() == 500){
                    if (list.size() >= delWebsiteFlyRecordQuery.getDelAmount()){
                        boolean flag = websiteGameService.delWebsiteFlyRecord(delWebsiteFlyRecordQuery);
                        JSONObject result = new JSONObject();
                        result.put("flag",flag);
                        return MrdJsonResult.ok(result);
                    }
                }else if (delWebsiteFlyRecordQuery.getDelAmount() == 1000){
                    if (list.size() >= delWebsiteFlyRecordQuery.getDelAmount()){
                        boolean flag = websiteGameService.delWebsiteFlyRecord(delWebsiteFlyRecordQuery);
                        JSONObject result = new JSONObject();
                        result.put("flag",flag);
                        return MrdJsonResult.ok(result);
                    }
                }
            }else{
                return MrdJsonResult.build1000("目前状态为关闭！");
            }
            return MrdJsonResult.build1000("最新记录无法删除！");
        }catch (Exception e){
            return MrdJsonResult.build1000("未设置站点设置值！");
        }
    }
    
    /**
     * 获取游戏封盘时间
     * @param account
     * @return
     */
    @PostMapping("/getGameSealTime")
    public JSONObject getGameSealTime(String account){
        if (StringUtils.isEmpty(account)){
            return MrdJsonResult.build503();
        }
        try {
            String sendGameSeal = sendGameSeal(account);
            System.out.println("------------"+sendGameSeal);
            JSONObject result = JSONObject.parseObject(sendGameSeal);
            return MrdJsonResult.ok(result);
        }catch (Exception e){
           return MrdJsonResult.build1000("链接超时,尝试重新登录！");
        }
    }

    /**
     * 获取PHP接口  效验管理账号
     * @param account
     * @param password
     * @return
     */
    private String sendFlyAdmin(String account,String password){
        Map<String, String> map = new HashMap(16);
        map.put("account", account);
        map.put("password", password);
        return HttpClientUtil.doPost(checkFlyAdmin,map);
    }

    /**
     * 获取PHP接口  游戏封盘时间
     * @param account
     * @return
     */
    private String sendGameSeal(String account){
        Map<String, String> map = new HashMap(16);
        map.put("account", account);
        return HttpClientUtil.doPost(sendGameSeal,map);
    }

    public static void main(String[] args) {

        String h = "say";

        if (h.contains("a")){
            System.out.println("1");
        }


        ArrayList<WebsiteFlyRecord> websiteFlyRecords = new ArrayList<>();
        WebsiteFlyRecord websiteFlyRecord = new WebsiteFlyRecord();
        for (int i = 0; i < 5; i++) {
            websiteFlyRecord.setNumber("2342");
            websiteFlyRecord.setAmount(new BigDecimal(i));
            websiteFlyRecord.setDetails("--");
            websiteFlyRecord.setWebsiteGameId(1);
            websiteFlyRecord.setWebsiteUserId(2);
            websiteFlyRecords.add(websiteFlyRecord);
        }


        ArrayList<Integer> is = new ArrayList<>();
        Integer n = new Integer(0);
        for (int i = 0; i < 5; i++) {
            n = i;
            is.add(n);
        }

        new Thread(new Runnable() {


                @Override
                public void run() {
                    for (int i = 0; i < 5; i++) {
                        try {
                            say("机器人1");
                            if (i ==1) {
                                continue;
                            }
                            Thread.sleep(3000);
                            System.out.println(DateUtils.DateToString(new Date(), DateUtils.formatStr_yyyyMMddHHmmss));

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();


//
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    for (int j = 0; j < 3; j++) {
//                        try {
//                            say("机器人2");
//                            Thread.sleep(5000);
//                            System.out.println(DateUtils.DateToString(new Date(), DateUtils.formatStr_yyyyMMddHHmmss));
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }).start();
        }



    public static synchronized void say(String r){
        System.out.println(Thread.currentThread().getName() + "->" + r + "：发言");
    }

}
